package com.hd123.rumba.qt;

import net.sf.hibernate.HibernateException;
import net.sf.hibernate.Session;
import net.sf.hibernate.SessionFactory;
import net.sf.hibernate.Transaction;
import net.sf.hibernate.cfg.Configuration;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;

import com.hd123.rumba.runtime.HibernateSession;

public class QueryResultSession {
  private static SessionFactory sessionFactory;
  protected static final ThreadLocal session = new ThreadLocal();

  // static {
  // try {
  // setEnabled("true");
  // } catch (Throwable th) {
  // throw new ExceptionInInitializerError(th);
  // }
  // }
  //
  // public static void setEnabled(String enabled) throws HibernateException {
  // if ("true".equals(enabled)) {
  // if (sessionFactory == null) {
  // Configuration conf = new Configuration().configure(QuerySourceSession.class
  // .getClassLoader().getResource("queryresult.cfg.xml"));
  // sessionFactory = conf.buildSessionFactory();
  // Logger.getLogger(QueryResultSession.class).info("QueryResult session
  // initialized.");
  // }
  // }
  // }

  public static void buildSessionFactory(Document doc) throws HibernateException {
    if (sessionFactory == null) {
      sessionFactory = new Configuration().configure(doc).buildSessionFactory();
      Logger.getLogger(QueryResultSession.class).info("--------------------------------");
      Logger.getLogger(QueryResultSession.class).info("QueryResult session initialized.");
      Logger.getLogger(QueryResultSession.class).info("--------------------------------");
    }
  }

  public static Session getSession() throws HibernateException {
    Session s = (Session) session.get();
    if (s == null) {
      Logger.getLogger(HibernateSession.class).debug(
          "QueryResultSsession_get." + Thread.currentThread().getId());
      s = sessionFactory.openSession();
      session.set(s);
    }
    return s;
  }

  public static void closeSession() throws HibernateException {
    Session s = (Session) session.get();
    session.set(null);
    if (s != null) {
      s.close();
      Logger.getLogger(HibernateSession.class).debug(
          "QueryResultSsession_close." + Thread.currentThread().getId());
    }
  }

  public static Transaction beginTransaction() throws HibernateException {
    return getSession().beginTransaction();
  }

  public static void commit(Transaction tx) throws HibernateException {
    tx.commit();
  }

  public static void rollback(Transaction tx) throws HibernateException {
    tx.rollback();
  }

  public static synchronized SessionFactory getSessionFactory() {
    return sessionFactory;
  }

}
